package com.jia.lightrailsystem

import android.util.Log
import android_serialport_api.SerialPort
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.io.UnsupportedEncodingException

/**
 *
 *  接受数据
 *
 *    private val scope = CoroutineScope(Dispatchers.IO)
 *
 *    fun received() {
 *         scope.launch {
 *             while (isActive) {
 *                 // 接受数据
 *                 UartUtil.onDataReceived()
 *             }
 *             withContext(Dispatchers.Main) {
 *                 ToastUtils.showLong("停止执行")
 *             }
 *         }
 *     }
 *
 *    scope.cancel()
 *
 * @Description：485通讯
 * @Author：jiayang
 * @Date：2023/10/16 15:34
 */
object UartUtil {

    private const val TAG = "uartUtil"
    private var mSerialPort: SerialPort? = null
    private var mOutputStream: OutputStream? = null
    private var mInputStream: InputStream? = null
//    private val scope = CoroutineScope(Dispatchers.IO)

    /**
     * Open uart
     *
     * @param device 设备号
     * @param baud 波特率
     */
    fun openUart(device: String, baud: Int) {
        try {
            mSerialPort = SerialPort(File(device), baud, 0)
            mInputStream = mSerialPort?.inputStream
            mOutputStream = mSerialPort?.outputStream
//            scope.launch {
//            onDataReceived()
//            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * On data send 发送数据
     *
     * @param data
     */
    fun onDataSend(data: CharSequence) {
        if (data == "") return
        try {
            val text = CharArray(data.length)
            for (i in data.indices) {
                text[i] = data[i]
            }
            val info = String(text).toByteArray(charset("GB2312"))
            Log.d(TAG, "onDataSend-->data=$data")
            mOutputStream?.write(info)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * On data received 接收数据flow 永久监听collect
     *
     * @return
     */

    suspend fun onDataReceived(): Flow<String> = flow {
        val buffer = ByteArray(1024)

        while (true) {
            if (mInputStream == null) {
                break
            }
            try {
                val size = withContext(Dispatchers.IO) { mInputStream?.read(buffer) ?: -1 }
                if (size > 0) {
                    try {
                        val data = String(buffer, 0, size, charset("GB2312"))
//                        Log.d(TAG, "onDataReceived-->data=$data")
                        emit(data)

                    } catch (e: UnsupportedEncodingException) {
                        // TODO Auto-generated catch block
                        e.printStackTrace()
                    }
                    println("mReception=" + String(buffer, 0, size))
                } else if (size < 0) {
                    // 如果读取到EOF，可能需要做一些清理工作，或者根据具体情况决定是否继续读取。
                    println("End of file reached.")
                } else if (Thread.interrupted()) {
                    // 如果线程被中断，抛出异常并清理资源。
                    throw IOException("Read operation interrupted.")
                }
            } catch (e: Exception) {
                // 处理其他可能的问题，例如输入流损坏等。
                e.printStackTrace()
            }
        }
    }

    /**
     * Close uart关闭串口
     *
     */
    fun closeUart() {
//        scope.cancel()
        mSerialPort?.close()
    }
}
